package com.quectel.business.contentaudit.baidu;

import com.quectel.business.common.thirdconfig.ThirdPlatformConfigBusiness;
import com.quectel.business.contentaudit.Validator;
import com.quectel.business.contentaudit.ValidatorContext;
import com.quectel.core.module.thirdconfig.dto.item.BaiduBCE;
import com.quectel.sdk.baidu.BaiduBCEClientBuilder;
import com.quectel.sdk.baidu.BaiduBCERequester;
import com.quectel.sdk.baidu.img.BaiduBCEImgClient;
import com.quectel.sdk.baidu.model.img.BaiduBCEImgResp;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.common.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/5/15 14:39
 * @description new java file header...
 */
@Component
@Slf4j
public class BaiduBCEImgValidatorImpl implements Validator<ValidatorContext> {
    public static final int BAIDU_BCE_IMG = 2;
    @Autowired
    private ThirdPlatformConfigBusiness thirdPlatformConfigBusiness;

    @Override
    public Response validate(ValidatorContext validatorContext) {

        log.debug("BaiduBCEValidatorImpl validate begin");

        BaiduBCE baiduBCEConfig = thirdPlatformConfigBusiness.getBaiduBCEConfig(validatorContext.getTenantId());
        if (baiduBCEConfig == null || !baiduBCEConfig.getImgEnable()) {
            return Response.ok();
        }
        if (CollectionUtils.isNotEmpty(validatorContext.getFilePaths())) {
            BaiduBCEImgClient bceImgClient = BaiduBCEClientBuilder.builder().host(BaiduBCERequester.HOST).apikey(baiduBCEConfig.getApiKey()).secretKey(baiduBCEConfig.getSecretKey()).build(BaiduBCEImgClient.class);
            for (String imgPath : validatorContext.getFilePaths()) {
                Response imgResponse = checkImgByPath(bceImgClient, imgPath);
                if (!imgResponse.isSuccess()) {
                    return imgResponse;
                }
            }
        }
        if(CollectionUtils.isNotEmpty(validatorContext.getImgUrls())){
            BaiduBCEImgClient bceImgClient = BaiduBCEClientBuilder.builder().host(BaiduBCERequester.HOST).apikey(baiduBCEConfig.getApiKey()).secretKey(baiduBCEConfig.getSecretKey()).build(BaiduBCEImgClient.class);
            for (String imgUrl : validatorContext.getImgUrls()) {
                Response imgResponse = checkImgByImgUrl(bceImgClient, imgUrl);
                if (!imgResponse.isSuccess()) {
                    return imgResponse;
                }
            }
        }

        log.debug("BaiduBCEValidatorImpl validate end");

        return Response.ok();
    }

    @Override
    public int getPriority() {
        return BAIDU_BCE_IMG;
    }

    @Override
    public Response invalidCache(ValidatorContext validatorContext) {
        return Response.ok();
    }

    private Response checkImgByPath(BaiduBCEImgClient client, String imgPath) {
        //构建请求器
        BaiduBCEImgClient.ImgInfo imgInfoByFile = client.getImgInfoByFile(imgPath);
        if (imgInfoByFile == null) {
            return Response.error("图片不存在");
        }
        Response response = client.requestPreCheck(imgInfoByFile);
        if (!response.isSuccess()) {
            return Response.error(response.getMessage());
        }
        BaiduBCEImgResp baiduBCEImgResp = client.checkByFile(imgInfoByFile.getImageData());
        if (baiduBCEImgResp == null) {
            return Response.error("请求第三方接口异常");
        }
        if (StringUtils.isNotBlank(baiduBCEImgResp.getErrorCode()) || StringUtils.isNotBlank(baiduBCEImgResp.getErrorMsg())) {
            return Response.error("请求第三方接口异常，errorCode：{" + baiduBCEImgResp.getErrorCode() + "}，errorMsg：{" + baiduBCEImgResp.getErrorMsg() + "}");
        }
        log.debug("checkText response : {}", JacksonUtils.toJsonString(baiduBCEImgResp));
        if (baiduBCEImgResp.getConclusionType() != BaiduBCEImgClient.PASS_CHECK) {
            return Response.error(baiduBCEImgResp.getConclusion());
        }
        return Response.ok();
    }

    private Response checkImgByImgUrl(BaiduBCEImgClient client, String imgUrl) {
        //构建请求器
        BaiduBCEImgClient.ImgInfo imgInfoByFile = client.getImgInfoByURL(imgUrl);
        if (imgInfoByFile == null) {
            return Response.error("图片不存在");
        }
        Response response = client.requestPreCheck(imgInfoByFile);
        if (!response.isSuccess()) {
            return Response.error(response.getMessage());
        }
        BaiduBCEImgResp baiduBCEImgResp = client.checkByImgUrl(imgUrl);
        if (baiduBCEImgResp == null) {
            return Response.error("请求第三方接口异常");
        }
        if (StringUtils.isNotBlank(baiduBCEImgResp.getErrorCode()) || StringUtils.isNotBlank(baiduBCEImgResp.getErrorMsg())) {
            return Response.error("请求第三方接口异常，errorCode：{" + baiduBCEImgResp.getErrorCode() + "}，errorMsg：{" + baiduBCEImgResp.getErrorMsg() + "}");
        }
        log.debug("checkText response : {}", JacksonUtils.toJsonString(baiduBCEImgResp));
        if (baiduBCEImgResp.getConclusionType() != BaiduBCEImgClient.PASS_CHECK) {
            return Response.error(baiduBCEImgResp.getConclusion());
        }
        return Response.ok();
    }
}
